package redis

import (
	"fmt"
	"log"
	"net/url"
	"strconv"
	"vov.cx/lib/env"
)

func getDSN() (dsn DSN) {
	var (
		uri      = env.GetString(keyRedisDSN,"redis://localhost")
		host     = env.GetString(keyRedisHost)
		port     = env.GetInt(keyRedisPort)
		user     = env.GetString(keyRedisUsr)
		password = env.GetString(keyRedisPwd)
		db       = env.GetInt(keyRedisDB, -1)
	)

	if uri != "" {
		if redisURI, err := url.Parse(uri); redisURI != nil {
			dsn.Host = redisURI.Hostname()
			dsn.Port, _ = strconv.Atoi(redisURI.Port())
			dsn.User = redisURI.User.Username()
			dsn.Password, _ = redisURI.User.Password()
			dsn.DB, _ = strconv.Atoi(redisURI.Path)
		} else {
			log.Printf("parse redis uri: %v", err)
		}
	}

	if host != "" {
		dsn.Host = host
	}

	if port > 0 {
		dsn.Port = int(port)
	}

	if user != "" {
		dsn.User = user
	}

	if password != "" {
		dsn.Password = password
	}

	if db >= 0 {
		dsn.DB = int(db)
	}

	if dsn.Host == "" {
		dsn.Host = "127.0.0.1"
	}

	if dsn.Port <= 0 {
		dsn.Port = 6379
	}

	if dsn.DB < 0 {
		dsn.DB = 0
	}

	return
}

type DSN struct {
	Host     string
	Port     int
	User     string
	Password string
	DB       int
}

func (dsn *DSN) HasAuth() bool {
	return dsn.Password != ""
}

func (dsn *DSN) AuthArgs() []interface{} {
	authArgs := make([]interface{}, 0, 2)
	if dsn.User != "" {
		authArgs = append(authArgs, dsn.User)
	}
	authArgs = append(authArgs, dsn.Password)
	return authArgs
}

func (dsn *DSN) Address() string {
	return fmt.Sprintf("%s:%d", dsn.Host, dsn.Port)
}
